<template>
  <el-dialog :append-to-body="true" :visible.sync="dialog" :title.sync="title" width="960px">
    <el-form ref="form" :model="form" :inline="true" :rules="rules" size="small" label-width="135px">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="统一社会信用代码" prop="seproCode">
            <el-input v-model="form.seproCode" class="input_text" :readonly="isView || isVerify" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="服务商分类" prop="seproId">
            <el-select v-model="form.seproId" placeholder="服务商分类" class="input_text" :disabled="isView && !isVerify" @change="indexSelect($event)">
              <el-option v-for="(item,index) in seproItem" :key="index" :label="item.label" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="服务商简称" prop="seproRefeName">
            <el-input v-model="form.seproRefeName" class="input_text" :readonly="isView || isVerify" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="服务商全称" prop="seproName">
            <el-input v-model="form.seproName" class="input_text" :readonly="isView || isVerify" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="邮政编码">
            <el-input v-model="form.postalCode" class="input_text" :readonly="isView || isVerify" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="详细地址" prop="address">
            <el-input v-model="form.address" class="input_text" :readonly="isView || isVerify" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="联系人" prop="contact">
            <el-input v-model="form.contact" class="input_text" :readonly="isView || isVerify" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="电子邮箱" prop="email">
            <el-input v-model="form.email" class="input_text" :readonly="isView || isVerify" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="手机号码" prop="phone">
            <el-input v-model="form.phone" class="input_text" :readonly="isView || isVerify" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="单位性质" prop="companyItemId">
            <el-select v-model="form.companyItemId" placeholder="单位性质" :disabled="isView || isVerify" @change="indexSelect($event)">
              <el-option v-for="(item,index) in comItem" :key="index" :label="item.label" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="注册资金（万元）" prop="registeredCapital">
            <el-input v-model="form.registeredCapital" class="input_text" :readonly="isView || isVerify" @keydown.native="myMoneyKeyDown" @input="moneyChange" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="法定代表人" prop="head">
            <el-input v-model="form.head" class="input_text" :readonly="isView || isVerify" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="服务范围" prop="serviceScope">
            <el-input v-model="form.serviceScope" class="input_text" :readonly="isView || isVerify" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="服务内容" prop="serviceContent">
            <el-input v-model="form.serviceContent" class="input_text" :readonly="isView || isVerify" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="备注">
            <el-input v-model="form.remark" class="input_text" :readonly="isView || isVerify" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="状态" prop="state">
            <el-radio v-for="item in dicts" :key="item.id" v-model="form.state" :label="item.id" :disabled="isView || isVerify">
              {{ item.name }}
            </el-radio>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="营业执照">
            <Upload ref="uploadRef" :limit="1" :file-list="form.lisence" :can-delete="!isVerify && !isView" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="邀请码" prop="inviteCode">
            <el-input v-model="form.inviteCode" style="width:180px;margin-right:15px" readonly></el-input>
            <el-button type="primary" :disabled="isView || isVerify" @click="handleResetInviteCode">重置邀请码</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <template v-if="!isVerify">
        <el-button v-show="isView===false || isAdd===true" type="text" @click="cancel">取消</el-button>
        <el-button v-show="isAdd===false && isView===true" :loading="loading" type="primary" @click="cancel">返回</el-button>
        <el-button v-show="isView===false" :loading="loading" type="primary" @click="doSubmit">确认</el-button>
      </template>
      <template v-else>
        <el-button :loading="loading" @click="doReturn">退回</el-button>
        <el-button :loading="loading" type="primary" @click="doPass">通过</el-button>
      </template>
    </div>
    <el-dialog
      width="560px"
      title="提示"
      :visible.sync="innerVisible"
      append-to-body
    >
      <el-input v-model="reason" type="textarea" placeholder="请输入退回原因" :rows="5"></el-input>
      <div slot="footer" class="dialog-footer">
        <el-button @click="innerVisible = false;">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确定</el-button>
      </div>
    </el-dialog>
  </el-dialog>
</template>

<script>
import request from '@/utils/request'
import { mapGetters } from 'vuex'
import { add, edit, verify, resetinvitecode } from '@/api/tServiceproviderInfo'
import { getToken } from '@/utils/auth'
import { validateNumber, isvalidPhone, isvalidEmail } from '@/utils/validate'
import Upload from '@/components/Upload';

export default {
  components: {
    Upload
  },
  props: {
    isAdd: {
      type: Boolean,
      required: true
    },
    isView: {
      type: Boolean,
      required: true
    },
    isVerify: { // 是否审核页：底部具有“通过”、“退回”两个按钮，审核页面中只允许对 “服务商分类”进行修改；
      type: Boolean,
      required: false
    },
    supThis: {
      type: Object,
      default: null
    }
  },
  data() {
    const validPhone = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入电话号码'))
      } else if (!isvalidPhone(value)) {
        callback(new Error('请输入正确的11位手机号码'))
      } else {
        callback()
      }
    }
    const validEmail = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入邮箱地址'))
      } else if (!isvalidEmail(value)) {
        callback(new Error('请输入正确的邮箱地址'))
      } else {
        callback()
      }
    }
    return {
      reason: '', // 审核拒绝原因
      innerVisible: false,
      loading: false,
      dialog: false,
      title: '',
      headers: {
        'Authorization': 'Bearer ' + getToken()
      },
      form: {
        id: '',
        seproCode: '',
        seproId: '',
        seproItemName: '',
        seproRefeName: '',
        seproName: '',
        postalCode: '',
        address: '',
        contact: '',
        email: '',
        phone: '',
        companyItemId: '',
        companyItemName: '',
        registeredCapital: '',
        head: '',
        serviceScope: '',
        serviceContent: '',
        remark: '',
        state: 1,
        inviteCode: '',
        lisence: '' // 营业执照
      },
      dicts: [
        // {
        //   id: 0,
        //   name: '待审核'
        // },
        {
          id: 1,
          name: '有效'
        },
        {
          id: 2,
          name: '无效'
        }
      ],
      seproItem: [],
      comItem: [],
      rules: {
        seproCode: [
          { required: true, message: '请输入服务商编码', trigger: 'blur' }
        ],
        seproId: [
          { required: true, message: '请选择服务商分类', trigger: 'blur' }
        ],
        seproRefeName: [
          { required: true, message: '请输入服务商简称', trigger: 'blur' }
        ],
        seproName: [
          { required: true, message: '请输入服务商全称', trigger: 'blur' }
        ],
        // postalCode: [
        //   { required: true, message: '请输入邮政编码', trigger: 'blur' }
        // ],
        address: [
          { required: true, message: '请输入详细地址', trigger: 'blur' }
        ],
        contact: [{ required: true, message: '请输入联系人', trigger: 'blur' }],
        email: [{ required: true, validator: validEmail, trigger: 'blur' }],
        phone: [{ required: true, validator: validPhone, trigger: 'blur' }],
        companyItemId: [
          { required: true, message: '请选择单位性质', trigger: 'blur' }
        ],
        registeredCapital: [
          { required: true, message: '请输入注册资金', trigger: 'blur' }
        ],
        head: [
          { required: true, message: '请输入主要负责人', trigger: 'blur' }
        ],
        serviceScope: [
          { required: true, message: '请输入服务范围', trigger: 'blur' }
        ],
        serviceContent: [
          { required: true, message: '请输入服务内容', trigger: 'blur' }
        ],
        state: [{ required: true, message: '请选择状态', trigger: 'blur' }]
      }
    }
  },
  computed: {
    ...mapGetters([
      'imagesUploadApi'
    ])
  },
  mounted: function() {
    this.byNameinfo('服务商类型', this.seproItem)
    this.byNameCominfo('单位性质', this.comItem)
    this.title = this.isAdd ? '新增' : (this.isView === true ? '详情' : '编辑')
  },
  methods: {
    handleResetInviteCode() {
      resetinvitecode({ inviteCode: this.form.inviteCode, id: this.form.id }).then((res) => {
        this.$message.success('重置成功');
        this.form.inviteCode = res.message;
        this.supThis.init()
      })
    },
    doReturn() {
      this.innerVisible = true
    },
    doPass() {
      verify({
        id: this.form.id,
        state: 1,
        reason: '',
        seproId: this.form.seproId
      }).then(() => {
        this.reason = ''
        this.supThis.init()
        this.innerVisible = false
        this.dialog = false
      })
    },
    handleConfirm() {
      if (!this.reason) {
        this.$message.warning('请输入退回原因')
        return
      }
      verify({
        id: this.form.id,
        state: 2,
        reason: this.reason,
        seproId: this.form.seproId
      }).then(() => {
        this.reason = ''
        this.supThis.init()
        this.innerVisible = false
        this.dialog = false
      })
    },
    byNameinfo(name, seproItem) {
      this.byName(name).then(res => {
        this.bydictId(res.id).then(resobject => {
          this.seproItem = resobject
        })
      })
    },
    byNameCominfo(name, comItem) {
      this.byName(name).then(res => {
        this.bydictId(res.id).then(resobject => {
          this.comItem = resobject
        })
      })
    },
    // 获取id值
    byName(name) {
      return request({
        url: 'api/dict/byName/' + name,
        method: 'get'
      })
    },
    // 获取id值
    bydictId(id) {
      return request({
        url: 'api/dictDetail/findByDeptId/' + id,
        method: 'get'
      })
    },
    indexSelect(event) {},
    cancel() {
      this.resetForm()
    },
    doSubmit() {
      // console.log(this.$refs.uploadRef.getPics());
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.loading = true
          if (this.isAdd) {
            this.doAdd()
          } else this.doEdit()
        } else {
          return false
        }
      })
    },
    doAdd() {
      add({ ...this.form, lisence: this.$refs.uploadRef.getPics() })
        .then(res => {
          this.resetForm()
          this.$notify({
            title: '添加成功',
            type: 'success',
            duration: 2500
          })
          this.loading = false
          this.$parent.$parent.init()
        })
        .catch(err => {
          this.loading = false
          console.log(err)
        })
    },
    doEdit() {
      edit({ ...this.form, lisence: this.$refs.uploadRef.getPics() })
        .then(res => {
          this.resetForm()
          this.$notify({
            title: '修改成功',
            type: 'success',
            duration: 2500
          })
          this.loading = false
          this.supThis.init()
        })
        .catch(err => {
          this.loading = false
          console.log(err)
        })
    },
    resetForm() {
      this.dialog = false
      this.$refs['form'].resetFields()
      this.form = {
        id: '',
        seproCode: '',
        seproId: '',
        seproItemName: '',
        seproRefeName: '',
        seproName: '',
        postalCode: '',
        address: '',
        contact: '',
        email: '',
        phone: '',
        companyItemId: '',
        companyItemName: '',
        registeredCapital: '',
        head: '',
        serviceScope: '',
        serviceContent: '',
        remark: '',
        state: '',
        lisence: ''
      }
    },
    myMoneyKeyDown(event) {
      validateNumber(event)
    },
    moneyChange(value) {
      var str = this.form.registeredCapital
      // 限制只能输入一个小数点
      if (str.indexOf('.') !== -1) {
        var str_ = str.substr(str.indexOf('.') + 1)
        if (str_.length > 2) {
          str = str.substr(0, str.indexOf('.') + 1) + str_.substr(0, 2)
        }
      }
      // str = str.replace(/\.\d\d\d$/,'') // 小数点后只能输两位
      this.form.registeredCapital = str
    }
  }
}
</script>

<style scoped>
.input_text {
  width: 300px;
}
</style>
